package com.hmdp.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public Result queryById(Long id) {
//        Shop shop = queryShopByIdWithPassThrough(id);//解决缓存穿透
//        Shop shop = queryShopByIdWithMutex(id);//互斥锁解决缓存击穿
        Shop shop = queryShopByIdWithLogicalExpire(id);//逻辑过期解决缓存击穿
        if (Objects.isNull(shop)) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 逻辑过期 解决缓存击穿
     *
     * @param id
     * @return
     */

    private Shop queryShopByIdWithLogicalExpire(Long id) {
        String shopCacheKey = CACHE_SHOP_KEY + id;
        String redisDateJson = (String) redisTemplate.opsForValue().get(shopCacheKey);
        //不存在直接返回空
        if (StrUtil.isBlank(redisDateJson)) {
            return null;
        }

        //命中的话判断是否过期
        RedisData redisData = JSONUtil.toBean(redisDateJson, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        LocalDateTime now = LocalDateTime.now();
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        //判断是否过期
        if (expireTime.isAfter(now)) {
            //未过期直接返回
            return shop;
        }
        //已经过期，构建缓存
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            try {
                //异步构建缓存
                threadPoolTaskExecutor.execute(() -> {
                    saveShop2(id, 20L);
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(lockKey);
            }
        }
        return shop;
    }


    /**
     * 互斥锁解决缓存击穿
     *
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(isLock);
    }

    private void unLock(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 互斥锁解决缓存击穿
     */
    private Shop queryShopByIdWithMutex(Long id) {
        String shopCacheKey = CACHE_SHOP_KEY + id;
        String shopJson = (String) redisTemplate.opsForValue().get(shopCacheKey);
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //我们缓存的空值
        if (shopJson != null) {
            return null;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        //构建缓存
        try {
            boolean isLock = tryLock(lockKey);
            if (isLock) {
                shop = getById(id);
                log.info("查询mysql");
                if (Objects.isNull(shop)) {
                    //缓存空值解决缓存穿透
                    redisTemplate.opsForValue().set(shopCacheKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                    return null;
                }
                ThreadUtil.sleep(200);//模拟构建缓存延迟
                redisTemplate.opsForValue().set(shopCacheKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            } else {
                //获取锁失败
                ThreadUtil.sleep(50);//过一会在获取
                queryShopByIdWithMutex(id);//尝试再次获取
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        return shop;
    }


    /**
     * 缓存穿透
     *
     * @param id
     * @return
     */
    private Shop queryShopByIdWithPassThrough(Long id) {
        String shopCacheKey = CACHE_SHOP_KEY + id;
        String cacheShopJson = (String) redisTemplate.opsForValue().get(shopCacheKey);
        //redis存直接返回
        if (StrUtil.isNotBlank(cacheShopJson)) {//只有在缓存中有数据时才返回
            log.info("redis查询成功");
            Shop shop = JSONUtil.toBean(cacheShopJson, Shop.class);
            return shop;
        }
        /**
         * 1.如果json为null 说明不是我们缓存的空值，而是在redis中没有查询到
         * 2.查出来的是 "" 说明就是我们缓存的空值
         */
        if (cacheShopJson != null) {
            log.info("我们缓存的空值");
            return null;
        }
        log.info("查询mysql");
        Shop shop = getById(id);
        if (Objects.isNull(shop)) {
            //缓存空值解决缓存穿透
            redisTemplate.opsForValue().set(shopCacheKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        redisTemplate.opsForValue().set(shopCacheKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    @Override
    @Transactional
    public Result updateByShop(Shop shop) {
        boolean b = update(shop, null);
        if (!b) {
            return Result.fail("更新失败");
        }
        String cacheShop = CACHE_SHOP_KEY + shop.getId();
        redisTemplate.delete(cacheShop);//删除缓存
        return Result.ok("更新成功");
    }

    public void saveShop2(Long id, Long expireTime) {
        ThreadUtil.sleep(200);
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        LocalDateTime now = LocalDateTime.now();
        redisData.setExpireTime(now.plusSeconds(expireTime));
        redisData.setData(shop);
        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));

    }
}
